using System;
using System.Collections.Generic;
using System.Text;
using System.Windows.Data;
using System.Globalization;

namespace Yorrick.Common
{
   /// <summary>
   /// Provides for two way binding between an <see cref="Enum"/> property and a 
   /// <see cref="Boolean"/> value. The value <c>true</c> corresponds to a match with
   /// a specified <see cref="Enum"/> value, the value <c>false</c> means it doesn't match.
   /// </summary>
   public class EnumMatchToBooleanConverter : IValueConverter
   {
      #region IValueConverter Members
      /// <summary>
      /// Returns whether or not the target value matches the parameter value.
      /// </summary>
      /// <param name="value">The value that should be checked.</param>
      /// <param name="targetType">Not used.</param>
      /// <param name="parameter">The enum value that <paramref name="value"/> should be equal to.</param>
      /// <param name="culture">Not used.</param>
      /// <returns><c>True</c> when it matches, <c>false</c> otherwise.</returns>
      public object Convert(object value, Type targetType, object parameter, CultureInfo culture)
      {
         if (value == null || parameter == null)
         {
            return false;
         }

         string checkValue = value.ToString();
         string targetValue = parameter.ToString();

         return checkValue.Equals(targetValue, StringComparison.OrdinalIgnoreCase);
      }

      /// <summary>
      /// Returns the <see cref="Enum"/> value that matches the specified string <paramref name="targetValue"/>
      /// if <paramref name="value"/> is <c>true</c>. Returns <c>null</c> otherwise.
      /// </summary>
      /// <param name="value">A <see cref="Boolean"/> value.</param>
      /// <param name="targetType">The subtype of <see cref="Enum"/> to which the
      /// value should be converted.</param>
      /// <param name="parameter">The <see cref="String"/> that indicates the value
      /// that should be parsed as a <see cref="Enum"/> of type <paramref name="targetType"/>.</param>
      /// <param name="culture">Not used.</param>
      /// <returns>The <see cref="Enum"/> value that matches the specified string <paramref name="targetValue"/>
      /// if <paramref name="value"/> is <c>true</c>. Returns <c>null</c> otherwise.</returns>
      public object ConvertBack(object value, Type targetType, object parameter, CultureInfo culture)
      {
         if (value == null || parameter == null)
         {
            return null;
         }

         bool useValue = (bool)value;
         string targetValue = parameter.ToString();
         if (useValue)
         {
            return Enum.Parse(targetType, targetValue);
         }
         return null;
      }
      #endregion
   }
}
